/*
 * @Author: Zhouhai 497675647@qq.com
 * @Date: 2023-02-10 20:57:34
 * @LastEditors: Zhouhai 497675647@qq.com
 * @LastEditTime: 2023-03-03 13:52:29
 */
import Taro from '@tarojs/taro';
import constant from '@/servers/constant';
import getBaseUrl from './baseUrl';
import interceptors from './interceptors';


interceptors.forEach(interceptorItem => Taro.addInterceptor(interceptorItem))

class httpRequest {

  baseOptions(params: any, method: string = "GET", headers: any = {}) {

    let { url, data } = params;

    // 是否需要设置 token
    const isToken = headers.isToken === false
    // 是否需要防止数据重复提交
    const isRepeatSubmit = headers.repeatSubmit === false

    const token = Taro.getStorageSync(constant.token)
    if (token && !isToken && headers) {
      headers['Authorization'] = 'Bearer ' + token // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    const contentType = headers.contentType
    if (!contentType) {
      headers['content-type'] = 'application/json;charset=utf-8'
    }


    if (!isRepeatSubmit && (method === 'POST' || method === 'PUT')) {
      const requestObj = {
        url: url,
        data: typeof data === 'object' ? JSON.stringify(data) : data,
        time: new Date().getTime()
      }
      const sessionObj =Taro.getStorageSync('sessionObj')
      if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
        Taro.setStorageSync('sessionObj', requestObj)
      } else {
        const s_url = sessionObj.url;                  // 请求地址
        const s_data = sessionObj.data;                // 请求数据
        const s_time = sessionObj.time;                // 请求时间
        const interval = 1000;                         // 间隔时间(ms)，小于此时间视为重复提交
        if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
          const message = '数据正在处理，请勿重复提交';
          console.warn(`[${s_url}]: ` + message)
          return Promise.reject(new Error(message))
        } else {
          Taro.setStorageSync('sessionObj', requestObj)
        }
      }
    }

    
    const BASE_URL = getBaseUrl(url);
    const option: any = {
      url: BASE_URL + url,
      data: data,
      method: method,
      header: headers
    };
    return Taro.request(option);
  }

  get(url: string, data: any = "", headers?: any) {
    let option = { url, data, headers };
    return this.baseOptions(option);
  }

  post(url: string, data?: any,  headers?: any) {
    let params = { url, data, headers };
    return this.baseOptions(params, "POST");
  }

  put(url: string, data: any = "", headers?: any) {
    let option = { url, data, headers };
    return this.baseOptions(option, "PUT");
  }

  delete(url: string, data: any = "", headers?: any) {
    let option = { url, data, headers };
    return this.baseOptions(option, "DELETE");
  }

}

export default new httpRequest()
